package com.dream.cgomall.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final String PreRole="ROLE_";
    @Autowired
    UserDetailsService userDetailsService;

    // @Bean
    // public PersistentTokenRepository persistentTokenRepository(){
    //     JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
    //     PersistentTokenRepository
    //     jdbcTokenRepository.setJdbcTemplate(redisTemplate);
    // }
    // @Override
    // protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //     auth.userDetailsService(userDetailsService).passwordEncoder(password());
    // }

    // @Bean
    // PasswordEncoder password() {
    //     return new BCryptPasswordEncoder();
    // }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/error/unauth"); //没有权限访问页面
        http.formLogin()
                .loginPage("/login.vue") //登录页面设置
                .loginProcessingUrl("/pages/public/login") //登录访问路径
                .defaultSuccessUrl("/").permitAll()
                .and().authorizeRequests()
                    .antMatchers("/**").permitAll()
                    .antMatchers("/backend/login").hasAuthority("admin")
                    .antMatchers("/backend/login").hasAnyAuthority("ROLE_ADMIN")
                    .antMatchers("/backend/login").hasAnyRole(PreRole+"admin",PreRole+"")
                .and().csrf().disable();
        //开启跨域访问
        http.cors().disable();
   //     http.logout().logoutUrl("/logout").logoutSuccessUrl("/").permitAll();//退出url
        http.headers().frameOptions().sameOrigin();
    }
}
